package com.ruoyi.messages;

import com.ruoyi.SpringWebSocket.MyWsHandler;
import com.ruoyi.agent.domain.SysAgent;
import com.ruoyi.agent.mapper.SysAgentMapper;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.messages.domain.SysBalanceWarning;
import com.ruoyi.messages.domain.SysNotify;
import com.ruoyi.messages.mapper.SysBalanceWarningMapper;
import com.ruoyi.messages.mapper.SysNotifyMapper;
import com.ruoyi.orderParent.domain.SysOrder;
import com.ruoyi.orderParent.domain.SysOrderParent;
import com.ruoyi.store.domain.SysStore;
import com.ruoyi.store.mapper.SysStoreMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.List;

/**
 * @Description:
 * @Author: 吕宇宏
 * @Date: 2024/7/30 10:00
 */
@Component
public class NotifyUtils {

    @Autowired
    private SysStoreMapper sysStoreMapper;
    @Autowired
    private SysAgentMapper agentMapper;
    @Autowired
    private SysBalanceWarningMapper balanceWarningMapper;
    @Autowired
    private SysNotifyMapper sysNotifyMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MyWsHandler myWsHandler;

    public NotifyUtils(SysStoreMapper sysStoreMapper, SysAgentMapper agentMapper, SysBalanceWarningMapper balanceWarningMapper, SysNotifyMapper sysNotifyMapper, RedisTemplate redisTemplate, MyWsHandler myWsHandler) {
        this.sysStoreMapper = sysStoreMapper;
        this.agentMapper = agentMapper;
        this.balanceWarningMapper = balanceWarningMapper;
        this.sysNotifyMapper = sysNotifyMapper;
        this.redisTemplate = redisTemplate;
        this.myWsHandler = myWsHandler;
    }

    //检查当前的店铺是否余额不足
    @Async("AsyncPool")
    @Transactional
    public void CheckStorePrice(Long deptId) {

        //通过deptId查询到对应商铺对象的余额值
        List<SysStore> sysStores = sysStoreMapper.selectSysStoreByDeptId(deptId);
        if (!CollectionUtils.isEmpty(sysStores)) {

            SysStore sysStore = sysStores.get(0);
            BigDecimal storeBalance = sysStore.getBalance();
            //通过店铺id查询到对应的代理商，通过代理商deptid查询余额预警表的预警值，进行比对

            Long agentId = sysStore.getAgentId();
            Long agentDeptId;
            if (agentId!=0) {
                //说明是代理商下的店铺
                SysAgent sysAgent = agentMapper.selectSysAgentById(agentId);
                agentDeptId = sysAgent.getDeptId();
            }else {
                //就是管理商下的店铺
                agentDeptId = 100l;
            }

            List<SysBalanceWarning> balanceWarnings= balanceWarningMapper.selectSysBalanceWarningByDeptId(agentDeptId);

            //todo 当创建代理商时默认插入预警值 默认100
            if (CollectionUtils.isEmpty(balanceWarnings)) {
                throw new ServiceException("代理商未设置预警余额值");
            }
            BigDecimal warningValue = balanceWarnings.get(0).getWarningValue();
            //如果不足则新增一条消息并发送消息给对应的用户和代理商
            if (storeBalance.compareTo(warningValue)!=1) {
                //说明余额小于等于预警值，应该发送了

                //创建一条消息：
                SysNotify sysNotify = new SysNotify().setType("0").setName("商铺: " + sysStore.getName() + "剩余余额：" + storeBalance + ",不足于：" + warningValue + ",请尽快充值")
                        .setDataId(sysStore.getId()).setUserId(sysStore.getUserId()).setDeptId(sysStore.getDeptId());
                //插入数据库中
                //发送信息给对应用
                sysNotify.setCreateTime(DateUtils.getNowDate());
                sysNotifyMapper.insertSysNotify(sysNotify);

                //向redis中设置(以代理商和商铺为单位)未读状态 (key:store_storeid : 消息id ，是否已读)

                Long storeId = sysStore.getId();
                String storeKey = "notify_store_"+storeId;
                String agentKye = "notify_agent_"+agentId;
                HashOperations hashOperations = redisTemplate.opsForHash();
                //0表示未读，当已读后会删除该小key
                hashOperations.put(storeKey,sysNotify.getId().toString(),"0");   //商铺未读
                hashOperations.put(agentKye,sysNotify.getId().toString(),"0");   //代理商未读



                myWsHandler.sendNotify(sysNotify);


            }



        }

    }

    //当单个订单被下单
    @Async("AsyncPool")
    public void MakeOrder(SysOrder order){

        //产生一条消息
        SysNotify sysNotify = new SysNotify().setDeptId(order.getDeptId()).setUserId(order.getUserId()).setName("商家:" + order.getStoreName() + " ,消费：" + order.getAmount() + "元，背调订单编号：" + order.getNumber()).setType("1").setDataId(order.getId());
        sysNotify.setCreateTime(DateUtils.getNowDate());
        sysNotifyMapper.insertSysNotify(sysNotify);

        //向redis中插入未读信息：
        String storeKey = "notify_store_"+order.getStoreId();
        String agentKye = "notify_agent_"+order.getAgentId();
        HashOperations hashOperations = redisTemplate.opsForHash();
        //0表示未读，当已读后会删除该小key
        hashOperations.put(storeKey,sysNotify.getId().toString(),0);   //商铺未读
        hashOperations.put(agentKye,sysNotify.getId().toString(),0);   //代理商未读

        //发送信息给对应用

        myWsHandler.sendNotify(sysNotify);



    }

    //当批量订单被下单
    @Async("AsyncPool")
    public void MakeOrders(SysOrderParent orderParent){

        //产生一条消息
        SysNotify sysNotify = new SysNotify().setDeptId(orderParent.getDeptId()).setUserId(orderParent.getUserId()).setName("商家:" + orderParent.getStoreName() + " ,消费：" + orderParent.getAmount() + "元，批量订单批次号：" + orderParent.getNumber()).setType("2").setDataId(orderParent.getId());
        sysNotify.setCreateTime(DateUtils.getNowDate());
        sysNotifyMapper.insertSysNotify(sysNotify);

        //向redis中插入未读信息：
        String storeKey = "notify_store_"+orderParent.getStoreId();
        String agentKye = "notify_agent_"+orderParent.getAgentId();
        HashOperations hashOperations = redisTemplate.opsForHash();
        //0表示未读，当已读后会删除该小key
        hashOperations.put(storeKey,sysNotify.getId().toString(),0);   //商铺未读
        hashOperations.put(agentKye,sysNotify.getId().toString(),0);   //代理商未读

        //发送信息给对应用

        myWsHandler.sendNotify(sysNotify);



    }

    //候选人授权通知
    @Async("AsyncPool")
    public void UserAuthorized(SysOrder order) {

        //产生一条消息
        SysNotify sysNotify = new SysNotify().setDeptId(order.getDeptId()).setUserId(order.getUserId()).setName(order.getNumber()+" 候选人："+order.getCdName()+" 已授权").setDataId(order.getId()).setType("3");
        sysNotify.setCreateTime(DateUtils.getNowDate());
        sysNotifyMapper.insertSysNotify(sysNotify);

        //向redis中插入未读信息：
        String storeKey = "notify_store_"+order.getStoreId();
//        String agentKye = "notify_agent_"+order.getAgentId();
        HashOperations hashOperations = redisTemplate.opsForHash();
        //0表示未读，当已读后会删除该小key
        hashOperations.put(storeKey,sysNotify.getId().toString(),0);   //商铺未读
//        hashOperations.put(agentKye,sysNotify.getId(),0);   //代理商未读

        //发送信息给对应用

        myWsHandler.sendNotify(sysNotify);



    }

    //线上报告已出
    @Async("AsyncPool")
    public void reportMaked(SysOrder order,Long reportId) {

        //产生一条消息
        SysNotify sysNotify = new SysNotify().setDeptId(order.getDeptId()).setUserId(order.getUserId()).setName(order.getNumber()+" 候选人："+order.getCdName()+" 报告已出");
        sysNotify.setCreateTime(DateUtils.getNowDate());
        sysNotify.setCreateBy(order.getCreateBy());
        sysNotify.setType("4").setDataId(reportId);
        sysNotifyMapper.insertSysNotify(sysNotify);

        //向redis中插入未读信息：
        String storeKey = "notify_store_"+order.getStoreId();
//        String agentKye = "notify_agent_"+order.getAgentId();
        HashOperations hashOperations = redisTemplate.opsForHash();
        //0表示未读，当已读后会删除该小key
        hashOperations.put(storeKey,sysNotify.getId().toString(),0);   //商铺未读
//        hashOperations.put(agentKye,sysNotify.getId(),0);   //代理商未读

        //发送信息给对应用

        myWsHandler.sendNotify(sysNotify);



    }
}
